class SpaceJourney {
    constructor() {
        this.totalDays = 0;
        this.completedFollowUps = 0;
        this.startDate = null;
        this.isShowingHelpTip = false;
        this.noticeModal = null;
        this.reportDaysModal = null;
        this.uploadedFiles = [];
        this.isTrialGroup = false;
        this.isControlGroup = false;
        this.isViewerGroup = false;
        this.showingAssistantQR = false;

        // 航程日记相关状态
        this.currentDiary = null;          // 当前日记内容
        this.isAdvancedOptionsVisible = false;  // 高级选项显示状态
        this.needDiary = false;            // 是否需要记录航程日记
        this.needFollowUp = false;         // 是否需要填写跟进报告

        // 初始化检查点和模态框
        this.initModals();
    }

    initModals() {
        document.addEventListener('DOMContentLoaded', () => {
            const noticeModalEl = document.getElementById('gameNoticeModal');
            if (noticeModalEl) {
                this.noticeModal = new bootstrap.Modal(noticeModalEl, {
                    backdrop: 'static'
                });
            }
            const reportDaysModalEl = document.getElementById('reportDaysModal');
            if (reportDaysModalEl) {
                this.reportDaysModal = new bootstrap.Modal(reportDaysModalEl, {
                    backdrop: 'static'
                });
            }
        });
    }

    async init() {
        try {
            const response = await fetch('/apps/space-journey/status');
            const data = await response.json();

            if (data.success) {
                // 保存用户标识信息
                this.userId = data.userId;
                this.groupNo = data.groupNo;
                this.subjectNo = data.subjectNo;

                // 更新游戏状态
                this.totalDays = data.totalDays;
                this.completedFollowUps = data.completedFollowUps;
                this.startDate = data.startDate;
                this.finishTime = data.finishTime;
                this.isTrialGroup = data.isTrialGroup;
                this.isControlGroup = data.isControlGroup;
                this.isViewerGroup = data.isViewerGroup;
                this.needCheckIn = data.needCheckIn;
                this.needFollowUp = data.needFollowUp;
                this.status = data.status;

                // 检查今天是否已有日记记录
                await this.checkTodayDiary();
                await this.loadTodayDiary();
                await this.loadDiaryData(this.currentDiary);

                // 更新主控台界面
                this.updateCockpitUI();
            } else {
                console.error('获取游戏状态失败:', data.message);
                // 只有在welcomeView或cockpitView激活时才显示错误提示
                const activeView = document.querySelector('.game-view.active');
                if (activeView && (activeView.id === 'welcomeView' || activeView.id === 'cockpitView')) {
                    this.showNoticeModal('错误', data.message || '游戏状态获取失败，请刷新页面重试');
                }
            }
        } catch (error) {
            console.error('初始化失败:', error);
            // 只有在welcomeView或cockpitView激活时才显示错误提示
            const activeView = document.querySelector('.game-view.active');
            if (activeView && (activeView.id === 'welcomeView' || activeView.id === 'cockpitView')) {
                this.showNoticeModal('错误', '游戏初始化失败，请刷新页面重试');
            }
        }
    }

    // 检查今天是否已有日记记录
    async checkTodayDiary() {
        // 只有在已经开始旅程的情况下才需要检查
        if (!this.startDate || new Date(this.startDate) > new Date()) {
            this.needCheckIn = false;
            return;
        }

        try {
            const response = await fetch('/apps/space-journey/diaries/today');
            if (!response.ok) {
                throw new Error('获取今日航程日记失败');
            }

            const data = await response.json();
            if (data.success) {
                // 如果没有今日日记，则需要打卡
                this.needCheckIn = !data.diary;
                // 保存当前日记以供编辑使用
                this.currentDiary = data.diary;
            } else {
                // 如果获取失败，保持原有状态
                console.error('获取今日航程日记失败:', data.message);
            }
        } catch (error) {
            console.error('检查今日航程日记失败:', error);
            // 出错时不改变原有状态
        }
    }

    // 初始化主控台界面
    initCockpitView() {
        // 获取用户组类型
        const cockpitView = document.getElementById('cockpitView');
        if (!cockpitView) return;

        // 判断用户组类型
        const paramValue = cockpitView.querySelector('.param-value');
        if (!paramValue) return;

        this.isTrialGroup = paramValue.textContent.includes('试验组');
        this.isControlGroup = paramValue.textContent.includes('对照组');
        this.isViewerGroup = paramValue.textContent.includes('观察员');

        // 更新启动引擎按钮状态
        this.updateLaunchButtonState();
    }

    // 更新启动引擎按钮状态
    updateLaunchButtonState() {
        const launchBtn = document.querySelector('.launch-btn');
        if (!launchBtn) return;

        // 如果用户已退出或完成试验
        if (this.status === 4 || this.status === 9) {
            launchBtn.classList.remove('disabled', 'countdown', 'abort');
            launchBtn.classList.add('disabled');
            launchBtn.disabled = true;
            launchBtn.style.animation = 'none';
            if (this.status === 4) {
                launchBtn.innerHTML = `<i class="fas fa-exclamation-circle"></i><span>已退出试验</span>`;
            } else {
                launchBtn.innerHTML = `<i class="fas fa-check-circle"></i><span>已完成试验</span>`;
            }
            return;
        }

        // 如果已经设置了开始日期
        if (this.startDate) {
            const today = new Date();
            const startDate = new Date(this.startDate);

            if (startDate > today) {
                // 倒计时中
                const diffDays = Math.ceil((startDate - today) / (1000 * 60 * 60 * 24));
                launchBtn.classList.remove('disabled', 'abort');
                launchBtn.classList.add('countdown');
                launchBtn.disabled = false;
                launchBtn.style.animation = 'none';
                launchBtn.textContent = `倒计时中(${diffDays})`;
                return;
            } else {
                launchBtn.classList.remove('disabled', 'countdown');
                launchBtn.classList.add('abort');
                launchBtn.disabled = false;
                launchBtn.style.animation = 'none';
                launchBtn.innerHTML = `<i class="fas fa-exclamation-triangle"></i><span>退出试验</span>`;
                return;
            }
        }

        // 来到这里说明没有设置开始日期，检查是否可以启动引擎
        if (this.isTrialGroup || this.isControlGroup || this.isViewerGroup ) {
            // 观摩者可以直接启动引擎
            launchBtn.classList.remove('disabled', 'countdown', 'abort');
            launchBtn.disabled = false;
            launchBtn.innerHTML = `<i class="fas fa-rocket"></i><span>启动引擎</span>`;
        } else {
            // 默认禁用
            launchBtn.classList.add('disabled');
            launchBtn.classList.remove('countdown', 'abort');
            launchBtn.disabled = true;
            launchBtn.style.animation = 'none';
            launchBtn.innerHTML = `<i class="fas fa-rocket"></i><span>启动引擎</span>`;
        }
    }

    // 启动跃迁
    async startJump() {
        document.getElementById('cockpitView').classList.remove('active');
        document.getElementById('journeyView').classList.add('active');
    }

    // 显示通报日期
    showReportDays() {
        if (!this.reportDaysModal) return;

        // 获取通报日期列表容器
        const reportDaysList = document.querySelector('.report-days-list');
        if (!reportDaysList) return;

        // 清空列表
        reportDaysList.innerHTML = '';

        // 检查是否有通报日期数据
        if (!window.reportDaysData || !Array.isArray(window.reportDaysData)) {
            reportDaysList.innerHTML = '<p>暂无通报日期数据</p>';
            this.reportDaysModal.show();
            return;
        }

        // 填充通报日期列表
        const reportDaysHtml = window.reportDaysData.map(report => {
            const reportDate = new Date(report.date);
            const formattedDate = `${reportDate.getFullYear()}-${String(reportDate.getMonth() + 1).padStart(2, '0')}-${String(reportDate.getDate()).padStart(2, '0')}`;
            const isEnabled = report.enabled;

            return `
                <div class="report-day-item ${isEnabled ? 'enabled' : 'disabled'}">
                    <div class="report-day-info">
                        <span class="report-day-number">第 ${report.day} 天</span>
                        <span class="report-day-date">${formattedDate}</span>
                    </div>
                    <div class="report-day-status">
                        <span class="status-badge ${isEnabled ? 'badge bg-success' : 'badge bg-secondary'}">
                            ${isEnabled ? '可查看' : '未到达'}
                        </span>
                    </div>
                </div>
            `;
        }).join('');

        reportDaysList.innerHTML = reportDaysHtml;

        // 显示模态框
        this.reportDaysModal.show();
    }

    // 切换研究助理二维码显示
    toggleAssistantQR() {
        const destinationImage = document.getElementById('destinationImage');
        const assistantQrCode = document.getElementById('assistantQrCode');

        if (!destinationImage || !assistantQrCode) return;

        if (this.showingAssistantQR) {
            // 切换回目的地图片
            assistantQrCode.style.display = 'none';
            destinationImage.style.display = 'block';
        } else {
            // 切换到研究助理二维码
            destinationImage.style.display = 'none';
            assistantQrCode.style.display = 'block';
        }

        this.showingAssistantQR = !this.showingAssistantQR;
    }

    // 处理文件上传
    handleFileUpload() {
        const fileInput = document.getElementById('consentFileInput');
        const files = fileInput.files;
        const uploadArea = document.getElementById('uploadArea');
        const progressBar = uploadArea.querySelector('.upload-progress-bar');

        if (files.length === 0) return;

        let uploadedCount = 0;

        Array.from(files).forEach(async (file, index) => {
            try {
                progressBar.style.width = `${(index / files.length * 100)}%`;

                const formData = new FormData();
                formData.append('file', file);

                const response = await fetch('https://mall.totembio.cn/api/uploadMtaFile', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (result.status === 200) {
                    this.uploadedFiles.push({
                        url: result.data.src,
                        name: file.name
                    });
                    uploadedCount++;

                    if (uploadedCount === files.length) {
                        progressBar.style.width = '100%';
                        setTimeout(() => {
                            progressBar.style.width = '0%';
                        }, 1000);

                        // 启用上传按钮
                        document.getElementById('uploadConsentBtn').disabled = false;

                        // 显示上传的文件预览
                        this.updateFilePreview();
                    }
                } else {
                    throw new Error(result.message || '上传失败');
                }
            } catch (error) {
                this.showNoticeModal('错误', `文件 ${file.name} 上传失败: ${error.message}`);
            }
        });
    }

    // 更新文件预览
    updateFilePreview() {
        const filesGrid = document.getElementById('uploadedFilesGrid');

        if (this.uploadedFiles.length > 0) {
            filesGrid.innerHTML = this.uploadedFiles.map((file, index) => `
                <div class="uploaded-file-item">
                    <img src="${file.url}" alt="已上传的知情同意书">
                    <div class="remove-file" onclick="game.removeFile(${index})">
                        <i class="fas fa-times"></i>
                    </div>
                </div>
            `).join('');

            this.showHelpTip('通行证已上传，请填写补给地址并点击下方按钮发送', 'consent-tip');
        } else {
            filesGrid.innerHTML = '';
            document.getElementById('uploadConsentBtn').disabled = true;
        }
    }

    // 移除已上传的文件
    removeFile(index) {
        this.uploadedFiles.splice(index, 1);
        this.updateFilePreview();
    }

    // 初始化文件上传区域
    initFileUpload() {
        const uploadArea = document.getElementById('uploadArea');
        if (!uploadArea) return;

        // 处理拖拽事件
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, (e) => {
                e.preventDefault();
                e.stopPropagation();
            });
        });

        // 添加拖拽效果
        ['dragenter', 'dragover'].forEach(eventName => {
            uploadArea.addEventListener(eventName, () => {
                uploadArea.classList.add('dragover');
            });
        });

        ['dragleave', 'drop'].forEach(eventName => {
            uploadArea.addEventListener(eventName, () => {
                uploadArea.classList.remove('dragover');
            });
        });

        // 处理文件拖放
        uploadArea.addEventListener('drop', (e) => {
            const fileInput = document.getElementById('consentFileInput');
            fileInput.files = e.dataTransfer.files;
            this.handleFileUpload();
        });
    }

    // 初始化上传按钮状态
    initUploadButtonState() {
        // 获取上传按钮元素
        const uploadBtn = document.getElementById('uploadConsentBtn');
        if (!uploadBtn) return;

        // 检查是否已有上传的知情同意书
        if (this.uploadedFiles.length > 0) {
            uploadBtn.disabled = false;
        } else {
            uploadBtn.disabled = true;
        }

        // 初始化文件上传区域
        this.initFileUpload();
    }

    // 上传知情同意书
    async uploadConsent() {
        if (this.uploadedFiles.length === 0) {
            this.showNoticeModal('提示', '请先上传知情同意书');
            return;
        }

        // 获取受试人信息
        const name = document.getElementById('subjectName').value.trim();
        const gender = document.getElementById('subjectGender').value.trim();
        const age = document.getElementById('subjectAge').value.trim();

        // 获取补给地址信息
        const recipientName = document.getElementById('recipientName').value.trim();
        const recipientPhone = document.getElementById('recipientPhone').value.trim();
        const recipientAddress = document.getElementById('recipientAddress').value.trim();

        // 验证受试人信息
        if (!gender) {
            this.showNoticeModal('提示', '请选择受试人性别');
            return;
        }

        if (!age) {
            this.showNoticeModal('提示', '请填写受试人年龄');
            return;
        }

        if (age < 0 || age > 18) {
            this.showNoticeModal('提示', '受试人年龄必须在0-18岁之间');
            return;
        }

        // 验证补给地址信息
        if (!recipientName) {
            this.showNoticeModal('提示', '请填写收件人姓名');
            return;
        }

        if (!recipientPhone) {
            this.showNoticeModal('提示', '请填写联系电话');
            return;
        }

        // 简单的手机号验证
        const phonePattern = /^1[3-9]\d{9}$/;
        if (!phonePattern.test(recipientPhone)) {
            this.showNoticeModal('提示', '请填写正确的手机号码');
            return;
        }

        if (!recipientAddress) {
            this.showNoticeModal('提示', '请填写详细收货地址');
            return;
        }

        try {
            const response = await fetch('/apps/space-journey/upload-consent', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    consentFiles: JSON.stringify(this.uploadedFiles.map(file => file.url)),
                    name,
                    gender,
                    age,
                    recipientName,
                    recipientPhone,
                    recipientAddress
                })
            });

            const data = await response.json();

            if (data.success) {
                this.showHelpTip('通行证和补给地址已发送，等待星际总部确认', 'consent-tip');

                // 切换到场景二
                document.getElementById('consentView').classList.remove('active');
                document.getElementById('welcomeView').classList.add('active');
            } else {
                this.showNoticeModal('提示', data.message || '上传失败，请重试');
            }
        } catch (error) {
            console.error('上传知情同意书失败:', error);
            this.showNoticeModal('错误', '上传知情同意书失败，请重试');
        }
    }

    async confirmTrialGroup() {
        try {
            const response = await fetch('/apps/space-journey/confirm-group', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            const data = await response.json();

            if (data.success) {
                if (data.isTrialGroup || data.isControlGroup || data.isViewerGroup) {
                    // 试验组和对照组首次进入补给地址设置界面
                    await this.init();
                    document.getElementById('welcomeView').classList.remove('active');
                    document.getElementById('cockpitView').classList.add('active');
                    // 更新主控台UI
                    this.updateCockpitUI();
                } else {
                    this.showNoticeModal('注意', '您的试验编组尚未确认，请联系试验助理');
                }
            } else {
                this.showNoticeModal('试验组回复', data.message || '您暂时无法参与此项目');
            }
        } catch (error) {
            console.error('确认分组失败:', error);
            this.showNoticeModal('错误', '确认分组失败，请重试');
        }
    }

    updateUI() {
        // 检查当前激活的视图
        const activeView = document.querySelector('.game-view.active');
        if (!activeView) return;

        // 更新主控台界面（如果在cockpitView中）
        if (activeView.id === 'cockpitView') {
            this.updateCockpitUI();
        }
    }

    // 清理模态框
    cleanupModal(modalElement) {
        // 等待模态框动画完成后清理
        setTimeout(() => {
            // 手动移除模态框的backdrop
            const backdrop = document.querySelector('.modal-backdrop');
            if (backdrop) {
                backdrop.remove();
            }
            // 移除body上的modal相关类
            document.body.classList.remove('modal-open');
            document.body.style.removeProperty('padding-right');
        }, 300);
    }

    // 显示通知模态框
    showNoticeModal(title, message, callback = null) {
        if (!this.noticeModal) return;

        const modalEl = document.getElementById('gameNoticeModal');
        if (!modalEl) return;

        const modalTitle = modalEl.querySelector('.modal-title');
        const modalBody = modalEl.querySelector('.modal-body');

        modalTitle.textContent = title || '提示';
        modalBody.textContent = message || '';

        // 监听模态框隐藏事件
        const self = this;
        modalEl.addEventListener('hidden.bs.modal', function handler() {
            modalEl.removeEventListener('hidden.bs.modal', handler);
            self.cleanupModal(modalEl);
            if (callback) callback();
        });

        this.noticeModal.show();
    }

    showHelpTip(helpText, tipId="consent-tip") {
        // 如果动画正在进行中，直接返回
        if (this.isShowingHelpTip) return;

        //const welcomeMessage = document.querySelector('.welcome-message');
        const welcomeMessage = document.getElementById(tipId);
        if (!welcomeMessage) return;

        const originalText = welcomeMessage.innerHTML; //textContent;

        // 设置标志为true，表示动画开始
        this.isShowingHelpTip = true;

        welcomeMessage.classList.add('message-highlight');
        welcomeMessage.style.color = '#9bb7d4';
        //welcomeMessage.textContent = helpText;
        welcomeMessage.innerHTML = helpText;

        setTimeout(() => {
            welcomeMessage.classList.add('message-fade');
            setTimeout(() => {
                //welcomeMessage.textContent = originalText;
                welcomeMessage.innerHTML = originalText;
                welcomeMessage.style.color = '';
                welcomeMessage.classList.remove('message-highlight', 'message-fade');
                // 动画完成后重置标志
                this.isShowingHelpTip = false;
            }, 1000);
        }, 4000);
    }


    updateCockpitUI() {
        // 更新用户组信息
        const userGroupInfo = document.querySelector('.progress-text span:first-child');
        if (userGroupInfo) {
            userGroupInfo.textContent = `${this.userId}-${this.groupNo}`;
        }

        // 计算已经过去的天数和已记录的日记数
        let elapsedDays = 0;
        let remainingDays = 90;
        if (this.startDate) {
            const startDate = new Date(this.startDate);
            startDate.setHours(0, 0, 0, 0); // 设置为当天开始时间
            const today = new Date();
            today.setHours(0, 0, 0, 0); // 设置为当天开始时间
            elapsedDays = Math.floor((today - startDate) / (1000 * 60 * 60 * 24));
            remainingDays = Math.max(0, 90 - elapsedDays);
        }

        // 更新旅程状态
        const journeyStatus = document.querySelector('.progress-text span:nth-child(2)');
        if (journeyStatus) {
            journeyStatus.textContent = this.startDate && new Date(this.startDate) < new Date() ? '正在进行' : '等待开始';
        }

        // 更新剩余距离
        const remainingDistance = document.querySelector('.progress-text span:last-child');
        if (remainingDistance) {
            remainingDistance.textContent = this.startDate && new Date(this.startDate) < new Date()
                ? `还有${remainingDays}天`
                : '距离90天';
        }

        // 更新进度条
        const progressBar = document.querySelector('.journey-progress-bar .progress-bar');
        if (progressBar) {
            const progressPercentage = (elapsedDays / 90) * 100;
            progressBar.style.width = `${Math.min(100, progressPercentage)}%`;
            progressBar.setAttribute('aria-valuenow', elapsedDays);

            // 清除现有的随访标记
            const existingMarkers = progressBar.parentElement.querySelectorAll('.followup-marker');
            existingMarkers.forEach(marker => marker.remove());

            // 添加随访日期标记
            const followUpDays = [13, 27, 43, 57, 73, 87];
            const progressContainer = progressBar.parentElement;

            // 添加新的随访标记
            followUpDays.forEach(day => {
                const markerPosition = (day / 90) * 100;
                const marker = document.createElement('div');
                marker.className = 'followup-marker';
                marker.style.left = `${markerPosition}%`;
                marker.setAttribute('data-day', `第${day}天`);
                marker.title = `第${day}天随访`;
                progressContainer.appendChild(marker);
            });
        }

        // 更新进度统计
        const progressStats = document.querySelector('.progress-stats');
        if (progressStats) {
            const spans = progressStats.querySelectorAll('span');
            if (spans.length >= 2) {
                if (this.startDate && new Date(this.startDate) < new Date()) {
                    // 已出发状态
                    const startDateStr = new Date(this.startDate).toLocaleDateString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        timeZone: 'Asia/Shanghai'
                    }).split('/').join('-');
                    spans[0].textContent = startDateStr;

                    // 计算应完成的打卡数
                    const startDate = new Date(this.startDate);
                    startDate.setHours(0, 0, 0, 0);
                    const today = new Date();
                    today.setHours(0, 0, 0, 0);
                    const totalExpectedDays = Math.floor((today - startDate) / (1000 * 60 * 60 * 24)) + 1;
                    spans[1].textContent = `打卡：${this.totalDays || 0}/${totalExpectedDays}`;

                    // 计算应完成的随访数
                    const followUpDays = [13, 27, 43, 57, 73, 87];
                    const totalExpectedFollowUps = followUpDays.filter(day =>
                        Math.floor((today - startDate) / (1000 * 60 * 60 * 24)) >= day
                    ).length;
                    if (spans[2]) {
                        spans[2].textContent = `随访：${this.completedFollowUps || 0}/${totalExpectedFollowUps}`;
                    }
                } else {
                    // 未出发状态，不显示任何内容
                    spans[0].textContent = '';
                    spans[1].textContent = '';
                    if (spans[2]) {
                        spans[2].textContent = '';
                    }
                }
            }
        }

        // 更新主控台提示信息
        const cockpitMessage = document.getElementById('cockpitMessage');
        if (cockpitMessage) {
            if (this.status === 4) {
                cockpitMessage.innerHTML = "<p><span style='color:#dc3545;'>您已退出试验。</span> 您仍可以查看历史记录、完成随访和量表工具。</p>";
            } else if (this.status === 9) {
                cockpitMessage.innerHTML = "<p><span style='color:#28a745;'>恭喜您已完成试验！</span> 您仍可以查看历史记录、完成随访和量表工具。</p>";
            } else if (this.startDate && new Date(this.startDate) <= new Date()) {
                let msg = '';
                if (this.needCheckIn) msg += "<p><span style='color:red;'>注意：今天的日记还没开始记录！</span></p>";
                if (this.needFollowUp) msg += "<p><span style='color:red;'>注意：您有定期随访任务待完成！</span></p>";
                if (this.isTrialGroup) msg += "<p>试验组累计5天或连续3天未打卡即判为出组</p>";
                if (msg == '') msg = '<p>欢迎回到主控台，试验过程一切正常</p>';
                cockpitMessage.innerHTML = msg;
            } else {
                cockpitMessage.innerHTML = '<p>欢迎入组！对照组入组后可直接开始试验，试验组开始服用试剂后再点击开始试验</p>';
                if (this.isTrialGroup) cockpitMessage.innerHTML = "<p>欢迎入组，试验组<span style='color:#88b04b;'>开始服用试验用品后</span>点击开始试验</p>";
            }
        }

        // 更新发射按钮状态
        this.updateLaunchButtonState();

        // 更新其他按钮状态
        const checkinBtn = document.querySelector('.checkin-btn');
        const followupBtn = document.querySelector('.followup-btn');
        if (checkinBtn && followupBtn) {
            // 如果试验已经开始，或者已经退出/完成，则启用这些按钮
            const hasStarted = this.startDate && new Date(this.startDate) < new Date();
            const isFinished = this.status === 4 || this.status === 9;
            if (!hasStarted && !isFinished) {
                checkinBtn.classList.add('disabled');
                followupBtn.classList.add('disabled');
                checkinBtn.disabled = true;
                followupBtn.disabled = true;
            } else {
                checkinBtn.classList.remove('disabled');
                followupBtn.classList.remove('disabled');
                checkinBtn.disabled = false;
                followupBtn.disabled = false;
            }

            // 如果试验已完成，修改随访按钮文字
            if (this.status === 9) {
                followupBtn.innerHTML = '<i class="fas fa-clipboard-list"></i> 附加随访';
            } else {
                followupBtn.innerHTML = '<i class="fas fa-clipboard-list"></i> 巡检随访';
            }
        }
    }

    // 返回主控台
    async backToCockpit() {
        try {
            // 获取当前活动的视图
            const activeView = document.querySelector('.game-view.active');
            const cockpitView = document.getElementById('cockpitView');

            // 检查元素是否存在
            if (!activeView || !cockpitView) {
                console.error('找不到活动视图或主控台视图元素');
                return;
            }

            // 隐藏当前视图，显示主控台视图
            activeView.classList.remove('active');
            cockpitView.classList.add('active');

            // 即使状态更新失败，也尝试更新UI
            await this.init();
            this.updateCockpitUI();
        } catch (error) {
            console.error('返回主控台失败:', error);
            // 不要弹出警告，只在控制台记录错误
        }
    }

    // 前往航程日记界面
    goToJourney() {
        // 隐藏所有界面
        document.querySelectorAll('.game-view').forEach(view => {
            view.classList.remove('active');
        });

        // 显示星际旅程界面
        document.getElementById('journeyView').classList.add('active');
    }

    // 跳转到航程日记页面
    goToDiary() {
        document.querySelectorAll('.game-view').forEach(view => {
            view.classList.remove('active');
        });
        document.getElementById('diaryView').classList.add('active');
        this.loadTodayDiary();
        this.loadDiaryHistory();
    }

    // 初始化日记模态框
    initDiaryModal() {
        const modalEl = document.getElementById('diaryEditModal');
        if (modalEl) {
            this.diaryModal = new bootstrap.Modal(modalEl);

            // 初始化表单事件监听
            this.initDiaryFormEvents();
        }
    }

    // 初始化日记表单事件
    initDiaryFormEvents() {
        // 监听漏服选项
        ['morning', 'evening'].forEach(time => {
            const radioYes = document.getElementById(`${time}_dose_yes`);
            const radioNo = document.getElementById(`${time}_dose_no`);
            const reasonDiv = radioNo?.closest('.form-group')?.querySelector('.missed-reason');

            if (radioYes && radioNo && reasonDiv) {
                const handleDoseChange = () => {
                    reasonDiv.style.display = radioNo.checked ? 'block' : 'none';
                    if (!radioNo.checked) {
                        // 如果选择了"已服"，清空漏服原因
                        const reasonSelect = reasonDiv.querySelector('select');
                        const otherInput = reasonDiv.querySelector('input');
                        if (reasonSelect) reasonSelect.value = '';
                        if (otherInput) {
                            otherInput.value = '';
                            otherInput.style.display = 'none';
                        }
                    }
                };

                radioYes.addEventListener('change', handleDoseChange);
                radioNo.addEventListener('change', handleDoseChange);
            }
        });

        // 监听其它原因选项
        document.querySelectorAll('select[name$="missed_reason"]').forEach(select => {
            select.addEventListener('change', () => {
                const otherInput = select.parentElement.querySelector('input[name$="missed_other"]');
                if (otherInput) {
                    otherInput.style.display = select.value === '其它' ? 'block' : 'none';
                    if (select.value !== '其它') {
                        otherInput.value = '';
                    }
                }
            });
        });

        // 监听不良反应选项
        const sideEffectsSelect = document.querySelector('select[name="side_effects"]');
        const sideEffectsOther = document.querySelector('input[name="side_effects_other"]');
        if (sideEffectsSelect && sideEffectsOther) {
            sideEffectsSelect.addEventListener('change', () => {
                sideEffectsOther.style.display = sideEffectsSelect.value === '其它' ? 'block' : 'none';
                if (sideEffectsSelect.value !== '其它') {
                    sideEffectsOther.value = '';
                }
            });
        }

        // 监听训练类型"没有"选项
        const noneCheckbox = document.getElementById('type_none');
        if (noneCheckbox) {
            noneCheckbox.addEventListener('change', () => {
                const otherCheckboxes = document.querySelectorAll('input[name="training_types"]:not(#type_none)');
                otherCheckboxes.forEach(cb => {
                    cb.disabled = noneCheckbox.checked;
                    if (noneCheckbox.checked) {
                        cb.checked = false;
                    }
                });
            });
        }

        // 确保所有文本输入框可以输入
        document.querySelectorAll('input[type="text"], textarea').forEach(input => {
            input.removeAttribute('readonly');
            input.removeAttribute('disabled');
        });
    }

    // 打开日记编辑模态框
    editDiary() {

        if (!this.diaryModal) {
            this.initDiaryModal();
        }

        // 显示/隐藏试验组特定字段
        const trialGroupSection = document.querySelector('.trial-group-section');
        if (trialGroupSection) {
            trialGroupSection.style.display = this.isTrialGroup ? 'block' : 'none';
        }

        // 设置模态框标题显示日期
        const modalTitle = document.getElementById('diaryEditModalLabel');
        if (modalTitle) {
            const today = new Date();
            const dateStr = today.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
            modalTitle.textContent = `${dateStr} 航程日记`;
        }

        // 如果有当天的日记，加载数据

        if (this.currentDiary) {
            const content = this.currentDiary.content;
            this.loadDiaryData(content);
        } else {
            // 重置表单
            document.getElementById('diaryForm').reset();
        }

        // 确保下拉框的样式正确
        document.querySelectorAll('.form-select').forEach(select => {
            select.style.color = '#fff';
            select.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
        });

        this.diaryModal.show();
    }

    // 加载日记数据到表单
    loadDiaryData(diary) {
        if (!diary) return;

        const form = document.getElementById('diaryForm');
        if (!form) return;

        // 基本信息
        if (this.isTrialGroup) {
            // 试验组特有字段
            if (diary.morning_dose) {
                const morningDoseInput = form.querySelector(`input[name="morning_dose"][value="${diary.morning_dose}"]`);
                if (morningDoseInput) morningDoseInput.checked = true;
            }
            if (diary.evening_dose) {
                const eveningDoseInput = form.querySelector(`input[name="evening_dose"][value="${diary.evening_dose}"]`);
                if (eveningDoseInput) eveningDoseInput.checked = true;
            }
            if (diary.side_effects) {
                form.querySelector('select[name="side_effects"]').value = diary.side_effects;
            }
        }

        // 通用字段
        if (diary.training_duration) {
            form.querySelector('select[name="training_duration"]').value = diary.training_duration;
        }
        if (diary.progress) {
            form.querySelector('textarea[name="progress"]').value = diary.progress;
        }

        // 高级选项
        const advancedFields = [
            'stool_times', 'stool_type', 'stool_color', 'stool_abnormal',
            'breakfast', 'lunch', 'dinner',
            'appetite', 'appetite_note',
            'supplements',
            'sleep_duration', 'sleep_quality', 'sleep_note',
            'environment_changes', 'summary'
        ];

        let hasAdvancedContent = false;
        advancedFields.forEach(field => {
            const element = form.querySelector(`[name="${field}"]`);
            if (element && diary[field]) {
                element.value = diary[field];
                hasAdvancedContent = true;
            }
        });

        // 如果有高级选项内容，自动展开高级选项区域
        if (hasAdvancedContent) {
            const advancedContent = document.querySelector('.advanced-content');
            if (advancedContent) {
                advancedContent.style.display = 'block';
                const toggleBtn = document.querySelector('.advanced-toggle .btn');
                if (toggleBtn) {
                    toggleBtn.innerHTML = '<i class="fas fa-chevron-up"></i> 收起更多内容';
                }
            }
        }
    }

    // 加载今日航程日记
    async loadTodayDiary() {
        try {
            const response = await fetch('/apps/space-journey/diaries/today');
            if (!response.ok) {
                throw new Error('获取航程日记失败');
            }
            const data = await response.json();
            if (!data.success) {
                throw new Error(data.message || '获取航程日记失败');
            }

            // 更新今日日记UI
            this.updateTodayDiaryUI(data.diary);
            // 保存当前日记以供编辑使用
            this.currentDiary = data.diary;
            // 更新needCheckIn状态
            this.needCheckIn = !data.diary;
        } catch (error) {
            console.error('加载今日航程日记失败:', error);
            // 出错时也要更新UI显示
            this.updateTodayDiaryUI(null);
        }
    }

    // 更新今日航程日记界面
    updateTodayDiaryUI(diary) {
        const emptyPrompt = document.querySelector('.empty-diary-prompt');
        const summaryDiv = document.querySelector('.diary-summary');

        if (!diary || !diary.content) {
            // 显示空日记提示
            emptyPrompt.style.display = 'block';
            summaryDiv.style.display = 'none';
            return;
        }

        // 隐藏空日记提示，显示日记摘要
        emptyPrompt.style.display = 'none';
        summaryDiv.style.display = 'block';

        const content = typeof diary.content === 'string' ? JSON.parse(diary.content) : diary.content;
        let html = '';

        // 基本信息
        if (content.training_duration) {
            html += `<p><strong>训练时长：</strong>${content.training_duration}</p>`;
        }
        if (content.progress) {
            html += `<p><strong>进展情况：</strong>${content.progress}</p>`;
        }

        // 试验组特有信息
        if (this.isTrialGroup) {
            if (content.morning_dose) {
                html += `<p><strong>早餐后服用益星：</strong>${content.morning_dose}</p>`;
            }
            if (content.evening_dose) {
                html += `<p><strong>晚餐后服用益星：</strong>${content.evening_dose}</p>`;
            }
            if (content.side_effects && content.side_effects !== '无') {
                html += `<p><strong>不良反应：</strong>${content.side_effects}</p>`;
            }
        }

        // 添加编辑提示
        html += '<div class="edit-hint mt-2"><i class="fas fa-edit"></i> 点击继续编辑</div>';

        summaryDiv.innerHTML = html;
    }

    // 当前页码
    currentPage = 1;
    // 是否还有更多日记
    hasMoreDiaries = false;

    // 加载航程日记历史
    async loadDiaryHistory(page = 1) {
        try {
            const response = await fetch(`/apps/space-journey/diaries/history?page=${page}`);
            if (!response.ok) {
                throw new Error('获取历史航程日记失败');
            }
            const data = await response.json();

            if (data.success) {
                this.updateDiaryHistoryUI(data.diaries, page === 1);
                this.hasMoreDiaries = data.pagination.hasMore;
                this.currentPage = page;

                // 显示/隐藏加载更多按钮
                const loadMoreContainer = document.querySelector('.load-more-container');
                if (loadMoreContainer) {
                    loadMoreContainer.style.display = this.hasMoreDiaries ? 'block' : 'none';
                }
            } else {
                throw new Error(data.message || '获取历史航程日记失败');
            }
        } catch (error) {
            console.error('加载历史航程日记失败:', error);
            this.showNoticeModal('错误', error.message || '加载历史航程日记失败，请重试');
        }
    }

    // 加载更多日记
    async loadMoreDiaries() {
        if (this.hasMoreDiaries) {
            await this.loadDiaryHistory(this.currentPage + 1);
        }
    }

    // 更新航程日记历史列表
    updateDiaryHistoryUI(diaries, isFirstPage = true) {
        const listDiv = document.getElementById('diaryList');
        if (!listDiv) return;

        if (!diaries || diaries.length === 0) {
            if (isFirstPage) {
                listDiv.innerHTML = '<p class="empty-diary">暂无历史航程记录</p>';
            }
            return;
        }

        const content = diaries.map(diary => {
            const date = new Date(diary.diary_date).toLocaleDateString('zh-CN');
            const content = typeof diary.content === 'string' ? JSON.parse(diary.content) : diary.content;

            // 生成服用记录的星星图标
            const morningDose = content.morning_dose === '已服';
            const eveningDose = content.evening_dose === '已服';
            const doseStars = this.isTrialGroup ? `
                <div class="dose-stars">
                    <i class="fas fa-star ${morningDose ? 'active' : ''}" title="早餐后服用"></i>
                    <i class="fas fa-star ${eveningDose ? 'active' : ''}" title="晚餐后服用"></i>
                </div>
            ` : '';

            return `
                <div class="diary-item" onclick="game.showDiaryDetail(${JSON.stringify(diary).replace(/"/g, '&quot;')})">
                    <div class="diary-item-header">
                    <div class="diary-date-container">
                    <span class="diary-date">${date}</span>
                            ${doseStars}
                        </div>
                    </div>
                    <div class="diary-summary">
                        <p><strong>训练时长：</strong>${content.training_duration || '未记录'}</p>
                        <p><strong>进展记录：</strong>${content.progress || '未记录'}</p>
                    </div>
                </div>
            `;
                }).join('');

                    if (isFirstPage) {
                        listDiv.innerHTML = content;
                    } else {
                        listDiv.innerHTML += content;
                    }
        }

            // 显示日记详情
            showDiaryDetail(diary) {
                const modalEl = document.getElementById('diaryDetailModal');
                if (!modalEl) return;

                const contentDiv = modalEl.querySelector('.diary-detail-content');
                if (!contentDiv) return;

                const date = new Date(diary.diary_date).toLocaleDateString('zh-CN');
                let html = `<h4 class="mb-4">${date} 航程日记</h4>`;

                const content = diary.content;

                // 基本信息
                html += '<div class="basic-info mb-4">';
                html += '<h5>基本信息</h5>';
                if (content.training_duration) {
                    html += `<p><strong>训练时长：</strong>${content.training_duration}</p>`;
                }
                if (content.progress) {
                    html += `<p><strong>进展情况：</strong>${content.progress}</p>`;
                }

                // 试验组特有信息
                if (this.isTrialGroup) {
                    if (content.morning_dose) {
                        html += `<p><strong>早餐后服用益星：</strong>${content.morning_dose}</p>`;
                    }
                    if (content.evening_dose) {
                        html += `<p><strong>晚餐后服用益星：</strong>${content.evening_dose}</p>`;
                    }
                    if (content.side_effects) {
                        html += `<p><strong>不良反应：</strong>${content.side_effects}</p>`;
                    }
                }
                html += '</div>';

                // 详细记录
                const advancedFields = {
                    'stool_times': '大便次数',
                    'stool_type': '大便性状',
                    'stool_color': '大便颜色',
                    'stool_abnormal': '异常情况',
                    'breakfast': '早餐',
                    'lunch': '午餐',
                    'dinner': '晚餐',
                    'appetite': '食欲变化',
                    'appetite_note': '食欲说明',
                    'supplements': '营养补充',
                    'sleep_duration': '睡眠时长',
                    'sleep_quality': '睡眠质量',
                    'sleep_note': '睡眠说明',
                    'environment_changes': '环境变化',
                    'summary': '今日小结'
                };

                let hasAdvancedContent = false;
                let advancedHtml = '<div class="advanced-info"><h5>详细记录</h5>';

                for (const [field, label] of Object.entries(advancedFields)) {
                    if (content[field]) {
                        hasAdvancedContent = true;
                        advancedHtml += `<p><strong>${label}：</strong>${content[field]}</p>`;
                    }
                }
                advancedHtml += '</div>';

                if (hasAdvancedContent) {
                    html += advancedHtml;
                }

                contentDiv.innerHTML = html;

                const modal = new bootstrap.Modal(modalEl);
                modal.show();
            }

            // 切换高级选项显示状态
            toggleAdvancedOptions() {
                const content = document.querySelector('.advanced-content');
                const toggleBtn = document.querySelector('.advanced-toggle .btn');
                if (!content || !toggleBtn) return;

                this.isAdvancedOptionsVisible = !this.isAdvancedOptionsVisible;
                content.style.display = this.isAdvancedOptionsVisible ? 'block' : 'none';
                toggleBtn.innerHTML = this.isAdvancedOptionsVisible ?
                    '<i class="fas fa-chevron-up"></i> 收起可选内容' :
                    '<i class="fas fa-chevron-down"></i> 更多可选内容';
            }

            // 保存航程日记
            async saveDiary() {
                try {
                    const formData = new FormData(document.getElementById('diaryForm'));
                    const data = {};
                    for (let [key, value] of formData.entries()) {
                        if (key === 'training_types') {
                            if (!data[key]) {
                                data[key] = [];
                            }
                            data[key].push(value);
                        } else {
                            data[key] = value;
                        }
                    }

                    const response = await fetch('/apps/space-journey/diary', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(data)
                    });

                    if (!response.ok) {
                        throw new Error('保存失败');
                    }

                    // 关闭模态窗
                    const modal = bootstrap.Modal.getInstance(document.getElementById('diaryEditModal'));
                    modal.hide();

                    // 刷新日记显示
                    await this.loadTodayDiary();
                    await this.loadDiaryHistory();

                    // 更新游戏状态
                    await this.init();

                    // 更新needCheckIn状态为false，因为已经完成了今日打卡
                    this.needCheckIn = false;
                    this.updateCockpitUI();

                } catch (error) {
                    console.error('保存航程日记失败:', error);
                    this.showNoticeModal('保存失败', '记录星际航程时遇到问题，请重试');
                }
            }

            // 显示用户信息
            showUserInfo() {
                const userInfoUID = document.getElementById('userInfoUID');
                const userInfoSubjectNo = document.getElementById('userInfoSubjectNo');
                const userInfoGroupNo = document.getElementById('userInfoGroupNo');
                const userInfoGroupType = document.getElementById('userInfoGroupType');

                if (userInfoUID) userInfoUID.textContent = this.userId;
                if (userInfoSubjectNo) userInfoSubjectNo.textContent = this.subjectNo;
                if (userInfoGroupNo) userInfoGroupNo.textContent = this.groupNo;
                if (userInfoGroupType) {
                    let groupType = '未分组';
                    if (this.isTrialGroup) groupType = '试验组';
                    else if (this.isControlGroup) groupType = '对照组';
                    else if (this.isViewerGroup) groupType = '观察员';
                    userInfoGroupType.textContent = groupType;
                }

                const modalElement = document.getElementById('userInfoModal');
                const modal = new bootstrap.Modal(modalElement);

                // 监听模态框隐藏事件
                const self = this;
                modalElement.addEventListener('hidden.bs.modal', function handler() {
                    modalElement.removeEventListener('hidden.bs.modal', handler);
                    self.cleanupModal(modalElement);
                });

                modal.show();
            }

            // 呼叫基地
            callBase() {
                // 隐藏所有视图
                document.querySelectorAll('.game-view').forEach(view => {
                    view.classList.remove('active');
                });

                // 显示呼叫导航员视图，并设置为呼叫场景
                document.getElementById('welcomeView').classList.add('active');
                this.updateWelcomeView('call');
            }

            // 更新欢迎视图
            updateWelcomeView(scene = 'default') {
                const welcomeTip = document.getElementById('welcome-tip');
                const confirmBtn = document.querySelector('.contact-assistant .help-btn');
                const contactTip = document.querySelector('.contact-assistant .contact-tip');

                if (!welcomeTip || !confirmBtn || !contactTip) return;

                switch (scene) {
                    case 'abort':
                        welcomeTip.innerHTML = '已接通指挥基地要求紧急着陆';
                        contactTip.innerHTML = '请向导航员说明紧急状况 <i class="fa fa-question-circle" style="color:#88b04b"></i>';
                        confirmBtn.textContent = '完成通讯，返回主控台';
                        break;
                    case 'call':
                        welcomeTip.innerHTML = '已接通指挥基地提供任务协助';
                        contactTip.innerHTML = '请向导航员说明所需支持 <i class="fa fa-question-circle" style="color:#88b04b"></i>';
                        confirmBtn.textContent = '完成通讯，返回主控台';
                        break;
                    default:
                        welcomeTip.innerHTML = '导航员正在根据通行证<br>为你进行舰队编组';
                        contactTip.innerHTML = '联系导航员要求优先编组 <i class="fa fa-question-circle" style="color:#88b04b"></i>';
                        confirmBtn.textContent = '已确认编组，登舰出发';
                }
            }

            // 显示随访提示
            goToFollowUp() {
                // 如果试验已完成，检查是否到达完成后第90天
                if (this.status === 9 && this.finishTime) {
                    const finishDate = new Date(this.finishTime);
                    const followUpDate = new Date(finishDate.getTime() + 90 * 24 * 60 * 60 * 1000);
                    const today = new Date();
                    
                    if (today < followUpDate) {
                        // 计算还需要等待的天数
                        const daysRemaining = Math.ceil((followUpDate - today) / (1000 * 60 * 60 * 24));
                        const targetDateStr = `${followUpDate.getFullYear()}年${followUpDate.getMonth() + 1}月${followUpDate.getDate()}日`;
                        this.showNoticeModal('提示', `请在 ${targetDateStr}（还需等待${daysRemaining}天）开始的三天之内点击这里完成附加随访登记，即可解锁附加权益（建议设置好闹铃）。`);
                        return;
                    }
                }

                const cockpitView = document.getElementById('cockpitView');
                const followupView = document.getElementById('followupView');

                // 隐藏主控台视图，显示随访视图
                cockpitView.classList.remove('active');
                followupView.classList.add('active');

                // 加载随访记录
                this.loadFollowUps();
            }

            // 中止旅程
            abortJourney() {
                // 先关闭中止确认模态框
                const abortModalInstance = bootstrap.Modal.getInstance(document.getElementById('abortModal'));
                if (abortModalInstance) {
                    abortModalInstance.hide();
                }
            }

            // 加载随访记录
            async loadFollowUps() {
                try {
                    // 显示加载状态
                    document.getElementById('followup-list').innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin"></i> 正在加载随访记录...</div>';

                    // 获取待完成的随访任务
                    const pendingResponse = await fetch('/apps/space-journey/pending-followups');
                    const pendingData = await pendingResponse.json();

                    if (!pendingData.success) {
                        throw new Error(pendingData.message || '获取待完成随访任务失败');
                    }

                    // 获取所有随访记录
                    const response = await fetch('/apps/space-journey/followups');
                    const data = await response.json();

                    if (!data.success) {
                        throw new Error(data.message || '获取随访记录失败');
                    }

                    // 更新UI
                    this.updateFollowUpUI(data.followups, pendingData.pendingFollowups, data.startDate );
                } catch (error) {
                    console.error('加载随访记录失败:', error);
                    document.getElementById('followup-list').innerHTML = `<div class="alert alert-danger">加载随访记录失败: ${error.message}</div>`;
                }
            }

            // 更新随访UI
            updateFollowUpUI(followups, pendingFollowups, startDate ) {
                const followupList = document.getElementById('followup-list');
                followupList.innerHTML = '';

                // 如果没有随访记录，显示提示信息
                if (followups.length === 0 && pendingFollowups.length === 0) {
                    followupList.innerHTML = '<div class="alert alert-info">暂无随访记录</div>';
                    return;
                }

                // 首先显示待完成的随访任务
                if (pendingFollowups.length > 0) {
                    const pendingSection = document.createElement('div');
                    pendingSection.className = 'mb-4';
                    
                    // 根据试验状态显示不同的标题和提示
                    const isCompleted = this.status === 9;
                    let additionalInfo = '';
                    
                    if (isCompleted && this.finishTime) {
                        const finishDate = new Date(this.finishTime);
                        const followUpDate = new Date(finishDate.getTime() + 90 * 24 * 60 * 60 * 1000);
                        const finishDateStr = `${finishDate.getFullYear()}年${finishDate.getMonth() + 1}月${finishDate.getDate()}日`;
                        const followUpDateStr = `${followUpDate.getFullYear()}年${followUpDate.getMonth() + 1}月${followUpDate.getDate()}日`;
                        additionalInfo = `<div class="mt-2">
                            <small class="text-muted">
                                试验完成时间：${finishDateStr}<br>
                                附加随访时间：${followUpDateStr}
                            </small>
                        </div>`;
                    }
                    
                    pendingSection.innerHTML = `
                <h4 class="text-warning">
                    <i class="fas fa-exclamation-triangle"></i> 
                    待完成的${isCompleted ? '附加' : '巡检'}随访
                </h4>
                <div class="alert alert-warning">
                    您有 ${pendingFollowups.length} 个${isCompleted ? '附加' : ''}随访任务需要完成。
                    ${isCompleted ? '完成这些随访将帮助我们更好地评估试验效果。' : '请及时完成以确保您的星际旅程安全。'}
                    ${additionalInfo}
                </div>
            `;

                    const pendingList = document.createElement('div');
                    pendingList.className = 'list-group mb-4';

                    pendingFollowups.forEach(followup => {
                        const followupDate = new Date(followup.date);
                        const formattedDate = `${followupDate.getFullYear()}-${String(followupDate.getMonth() + 1).padStart(2, '0')}-${String(followupDate.getDate()).padStart(2, '0')}`;

                        const item = document.createElement('div');
                        item.className = 'list-group-item list-group-item-action';
                        item.innerHTML = `
                    <div class="d-flex w-100 justify-content-between">
                        <h5 class="mb-1">第 ${followup.day} 天巡检随访</h5>
                        <small class="text-danger">${followup.daysOverdue > 0 ? `逾期 ${followup.daysOverdue} 天` : '今日到期'}</small>
                    </div>
                    <p class="mb-1">计划日期: ${formattedDate}</p>
                    <button class="btn btn-primary btn-sm mt-2 complete-followup-btn" data-day="${followup.day}">
                        <i class="fas fa-clipboard-check"></i> 立即完成
                    </button>
                `;
                        pendingList.appendChild(item);
                    });

                    pendingSection.appendChild(pendingList);
                    followupList.appendChild(pendingSection);
                }

                // 显示已完成的随访记录
                const completedFollowups = followups.filter(f => f.completed);
                if (completedFollowups.length > 0) {
                    const completedSection = document.createElement('div');
                    const isCompleted = this.status === 9;
                    completedSection.innerHTML = `<h4 class="text-success">
                        <i class="fas fa-check-circle"></i> 
                        已完成的${isCompleted ? '附加' : '巡检'}随访
                    </h4>`;

                    const completedList = document.createElement('div');
                    completedList.className = 'list-group';

                    completedFollowups.forEach(followup => {
                        const targetDate = followup.targetDate ? new Date(followup.targetDate) : null;
                        const formattedTargetDate = targetDate ? `${targetDate.getFullYear()}-${String(targetDate.getMonth() + 1).padStart(2, '0')}-${String(targetDate.getDate()).padStart(2, '0')}` : '未知';

                        const actualDate = followup.date ? new Date(followup.date) : null;
                        const formattedActualDate = actualDate ? `${actualDate.getFullYear()}-${String(actualDate.getMonth() + 1).padStart(2, '0')}-${String(actualDate.getDate()).padStart(2, '0')}` : '未知';

                        const content = followup.content || {};

                        const item = document.createElement('div');
                        item.className = 'list-group-item';
                        const isCompleted = this.status === 9;
                        item.innerHTML = `
                    <div class="d-flex w-100 justify-content-between">
                        <h5 class="mb-1">第 ${followup.targetDay} 天${isCompleted ? '附加' : '巡检'}随访</h5>
                        <small class="text-muted">完成于 ${formattedActualDate}</small>
                    </div>
                    <p class="mb-1">计划日期: ${formattedTargetDate}</p>
                    <button class="btn btn-outline-secondary btn-sm mt-2 view-followup-btn" data-followup='${JSON.stringify(followup)}'>
                        <i class="fas fa-eye"></i> 查看详情
                    </button>
                `;
                        completedList.appendChild(item);
                    });

                    completedSection.appendChild(completedList);
                    followupList.appendChild(completedSection);
                }

                // 添加事件监听器
                document.querySelectorAll('.complete-followup-btn').forEach(btn => {
                    btn.addEventListener('click', () => {
                        const day = btn.getAttribute('data-day');
                        this.showFollowUpForm(day);
                    });
                });

                document.querySelectorAll('.view-followup-btn').forEach(btn => {
                    btn.addEventListener('click', () => {
                        const followup = JSON.parse(btn.getAttribute('data-followup'));
                        this.showFollowUpDetail(followup);
                    });
                });
            }

            // 显示随访表单
            showFollowUpForm(day) {
                // 创建模态框
                const modalId = 'followup-form-modal';
                let modalElement = document.getElementById(modalId);

                if (!modalElement) {
                    modalElement = document.createElement('div');
                    modalElement.className = 'modal fade';
                    modalElement.id = modalId;
                    modalElement.setAttribute('tabindex', '-1');
                    modalElement.setAttribute('aria-labelledby', `${modalId}-label`);
                    modalElement.setAttribute('aria-hidden', 'true');

                    modalElement.innerHTML = `
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="${modalId}-label">第 <span id="followup-day"></span> 天巡检随访</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="followup-form">
                                <!-- 1. 情绪状态 -->
                                <div class="mb-3">
                                    <label class="form-label">1. 情绪状态 (1=平静→5=爆发)</label>
                                    <div class="btn-group w-100" role="group">
                                        <input type="radio" class="btn-check" name="emotion_score" id="emotion1" value="1" required>
                                        <label class="btn btn-outline-primary" for="emotion1">1分</label>

                                        <input type="radio" class="btn-check" name="emotion_score" id="emotion2" value="2">
                                        <label class="btn btn-outline-primary" for="emotion2">2分</label>

                                        <input type="radio" class="btn-check" name="emotion_score" id="emotion3" value="3">
                                        <label class="btn btn-outline-primary" for="emotion3">3分</label>

                                        <input type="radio" class="btn-check" name="emotion_score" id="emotion4" value="4">
                                        <label class="btn btn-outline-primary" for="emotion4">4分</label>

                                        <input type="radio" class="btn-check" name="emotion_score" id="emotion5" value="5">
                                        <label class="btn btn-outline-primary" for="emotion5">5分</label>
                                    </div>
                                </div>

                                <!-- 2. 行为特征 -->
                                <div class="mb-3">
                                    <label class="form-label">2. 行为特征</label>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="behavior0" name="behaviors" value="行为正常">
                                        <label class="form-check-label" for="behavior0">行为正常</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="behavior1" name="behaviors" value="刻板动作">
                                        <label class="form-check-label" for="behavior1">刻板动作</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="behavior2" name="behaviors" value="社交回避">
                                        <label class="form-check-label" for="behavior2">社交回避</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="behavior3" name="behaviors" value="攻击行为">
                                        <label class="form-check-label" for="behavior3">攻击行为</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="behavior4" name="behaviors" value="自伤">
                                        <label class="form-check-label" for="behavior4">自伤</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="behavior5" name="behaviors" value="其它">
                                        <label class="form-check-label" for="behavior5">其它</label>
                                        <input type="text" class="form-control form-control-sm mt-1" id="behavior_other" name="behavior_other" maxlength="10" placeholder="请填写其它特征(10字内)">
                                    </div>
                                </div>

                                <!-- 3. 饮食记录 -->
                                <div class="mb-3">
                                    <label class="form-label">3. 饮食记录</label>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="diet1" name="diet" value="规律">
                                        <label class="form-check-label" for="diet1">规律</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="diet2" name="diet" value="挑食">
                                        <label class="form-check-label" for="diet2">挑食</label>
                                        <input type="text" class="form-control form-control-sm mt-1" id="diet_picky" name="diet_picky" placeholder="请填写主要食物">
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="diet3" name="diet" value="过敏">
                                        <label class="form-check-label" for="diet3">过敏</label>
                                        <input type="text" class="form-control form-control-sm mt-1" id="diet_allergy" name="diet_allergy" placeholder="请填写过敏食物">
                                    </div>
                                </div>

                                <!-- 4. 睡眠质量 -->
                                <div class="mb-3">
                                    <label class="form-label">4. 睡眠质量 (近3天平均值)</label>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="input-group mb-3">
                                                <span class="input-group-text">每日总时长</span>
                                                <input type="number" class="form-control" id="sleep_hours" name="sleep_hours" min="0" max="24" step="0.5" required>
                                                <span class="input-group-text">小时</span>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="input-group mb-3">
                                                <span class="input-group-text">中断次数</span>
                                                <input type="number" class="form-control" id="sleep_interruptions" name="sleep_interruptions" min="0" max="20" required>
                                                <span class="input-group-text">次</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- 5. 胃肠反应 -->
                                <div class="mb-3">
                                    <label class="form-label">5. 胃肠反应 (近一周最频繁症状)</label>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="gi_symptoms" id="gi0" value="正常">
                                        <label class="form-check-label" for="gi0">正常</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="gi_symptoms" id="gi1" value="便秘" required>
                                        <label class="form-check-label" for="gi1">便秘</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="gi_symptoms" id="gi2" value="腹泻">
                                        <label class="form-check-label" for="gi2">腹泻</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="gi_symptoms" id="gi3" value="腹胀">
                                        <label class="form-check-label" for="gi3">腹胀</label>
                                    </div>
                                </div>

                                <!-- 6. 感冒生病 -->
                                <div class="mb-3">
                                    <label class="form-label">6. 感冒生病（近一周内）</label>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="illness1" name="illness" value="无">
                                        <label class="form-check-label" for="illness1">无</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="illness2" name="illness" value="发热">
                                        <label class="form-check-label" for="illness2">发热</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="illness3" name="illness" value="咳嗽">
                                        <label class="form-check-label" for="illness3">咳嗽</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="illness4" name="illness" value="呕吐">
                                        <label class="form-check-label" for="illness4">呕吐</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="illness5" name="illness" value="其他">
                                        <label class="form-check-label" for="illness5">其他</label>
                                        <input type="text" class="form-control form-control-sm mt-1" id="illness_other" name="illness_other" placeholder="请填写说明">
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="illness6" name="illness" value="用药">
                                        <label class="form-check-label" for="illness6">用药</label>
                                        <input type="text" class="form-control form-control-sm mt-1" id="medication" name="medication" placeholder="请填写所用药物说明">
                                    </div>
                                </div>

                                <!-- 7. 咨询问题 -->
                                <div class="mb-3">
                                    <label for="consultation" class="form-label">7. 希望咨询主诊医生的问题</label>
                                    <textarea class="form-control" id="consultation" name="consultation" rows="3"></textarea>
                                </div>

                                <input type="hidden" id="followup-target-day">
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" id="submit-followup-btn">提交随访</button>
                        </div>
                    </div>
                </div>
            `;

                    document.body.appendChild(modalElement);

                    // 添加提交事件
                    document.getElementById('submit-followup-btn').addEventListener('click', () => {
                        this.submitFollowUp();
                    });

                    // 添加表单联动事件
                    document.getElementById('behavior5').addEventListener('change', function() {
                        document.getElementById('behavior_other').disabled = !this.checked;
                        if (!this.checked) document.getElementById('behavior_other').value = '';
                    });

                    document.getElementById('diet2').addEventListener('change', function() {
                        document.getElementById('diet_picky').disabled = !this.checked;
                        if (!this.checked) document.getElementById('diet_picky').value = '';
                    });

                    document.getElementById('diet3').addEventListener('change', function() {
                        document.getElementById('diet_allergy').disabled = !this.checked;
                        if (!this.checked) document.getElementById('diet_allergy').value = '';
                    });

                    document.getElementById('illness5').addEventListener('change', function() {
                        document.getElementById('illness_other').disabled = !this.checked;
                        if (!this.checked) document.getElementById('illness_other').value = '';
                    });

                    document.getElementById('illness6').addEventListener('change', function() {
                        document.getElementById('medication').disabled = !this.checked;
                        if (!this.checked) document.getElementById('medication').value = '';
                    });

                    document.getElementById('illness1').addEventListener('change', function() {
                        const illnessCheckboxes = document.querySelectorAll('input[name="illness"]');
                        if (this.checked) {
                            illnessCheckboxes.forEach(checkbox => {
                                if (checkbox.id !== 'illness1') {
                                    checkbox.checked = false;
                                    checkbox.disabled = true;

                                    // 清空并禁用相关输入框
                                    if (checkbox.id === 'illness5') document.getElementById('illness_other').value = '';
                                    if (checkbox.id === 'illness6') document.getElementById('medication').value = '';
                                }
                            });
                            document.getElementById('illness_other').disabled = true;
                            document.getElementById('medication').disabled = true;
                        } else {
                            illnessCheckboxes.forEach(checkbox => {
                                if (checkbox.id !== 'illness1') {
                                    checkbox.disabled = false;
                                }
                            });
                        }
                    });
                }

                // 初始化表单状态
                document.getElementById('behavior_other').disabled = true;
                document.getElementById('diet_picky').disabled = true;
                document.getElementById('diet_allergy').disabled = true;
                document.getElementById('illness_other').disabled = true;
                document.getElementById('medication').disabled = true;

                // 设置表单值
                document.getElementById('followup-day').textContent = day;
                document.getElementById('followup-target-day').value = day;
                document.getElementById('followup-form').reset();

                // 显示模态框
                const modal = new bootstrap.Modal(modalElement);
                modal.show();
            }

            // 提交随访
            async submitFollowUp() {
                try {
                    const form = document.getElementById('followup-form');

                    // 基本验证
                    if (!form.checkValidity()) {
                        form.reportValidity();
                        return;
                    }

                    const targetDay = document.getElementById('followup-target-day').value;

                    // 收集表单数据
                    const formData = new FormData(form);

                    // 处理多选项
                    const behaviors = [];
                    document.querySelectorAll('input[name="behaviors"]:checked').forEach(checkbox => {
                        behaviors.push(checkbox.value);
                    });

                    const diet = [];
                    document.querySelectorAll('input[name="diet"]:checked').forEach(checkbox => {
                        diet.push(checkbox.value);
                    });

                    const illness = [];
                    document.querySelectorAll('input[name="illness"]:checked').forEach(checkbox => {
                        illness.push(checkbox.value);
                    });

                    // 构建随访内容
                    const followupData = {
                        targetDay: parseInt(targetDay),
                        emotion_score: formData.get('emotion_score'),
                        behaviors: behaviors,
                        behavior_other: formData.get('behavior_other'),
                        diet: diet,
                        diet_picky: formData.get('diet_picky'),
                        diet_allergy: formData.get('diet_allergy'),
                        sleep_hours: formData.get('sleep_hours'),
                        sleep_interruptions: formData.get('sleep_interruptions'),
                        gi_symptoms: formData.get('gi_symptoms'),
                        illness: illness,
                        illness_other: formData.get('illness_other'),
                        medication: formData.get('medication'),
                        consultation: formData.get('consultation')
                    };

                    // 显示加载状态
                    const submitBtn = document.getElementById('submit-followup-btn');
                    const originalText = submitBtn.innerHTML;
                    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 提交中...';
                    submitBtn.disabled = true;

                    // 提交随访
                    const response = await fetch('/apps/space-journey/followup', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            targetDay,
                            followupContent: JSON.stringify(followupData)
                        })
                    });

                    const data = await response.json();

                    // 恢复按钮状态
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;

                    if (!data.success) {
                        throw new Error(data.message || '提交随访失败');
                    }

                    // 关闭模态框
                    bootstrap.Modal.getInstance(document.getElementById('followup-form-modal')).hide();

                    // 显示成功消息
                    this.showNoticeModal('随访提交成功', '感谢您完成巡检随访，您的星际旅程将更加安全！', () => {
                        // 重新加载随访记录
                        this.loadFollowUps();
                    });
                } catch (error) {
                    console.error('提交随访失败:', error);
                    alert(`提交随访失败: ${error.message}`);
                }
            }

            // 显示随访详情
            showFollowUpDetail(followup) {
                // 创建模态框
                const modalId = 'followup-detail-modal';
                let modalElement = document.getElementById(modalId);

                if (!modalElement) {
                    modalElement = document.createElement('div');
                    modalElement.className = 'modal fade';
                    modalElement.id = modalId;
                    modalElement.setAttribute('tabindex', '-1');
                    modalElement.setAttribute('aria-labelledby', `${modalId}-label`);
                    modalElement.setAttribute('aria-hidden', 'true');

                    modalElement.innerHTML = `
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="${modalId}-label">第 ${followup.targetDay} 天巡检随访</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body" id="followup-detail-content">
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                        </div>
                    </div>
                </div>
            `;

                    document.body.appendChild(modalElement);
                }

                // 设置详情内容
                const content = followup.content || {};
                const targetDate = followup.targetDate ? new Date(followup.targetDate) : null;
                const formattedTargetDate = targetDate ? `${targetDate.getFullYear()}-${String(targetDate.getMonth() + 1).padStart(2, '0')}-${String(targetDate.getDate()).padStart(2, '0')}` : '未知';

                const actualDate = followup.date ? new Date(followup.date) : null;
                const formattedActualDate = actualDate ? `${actualDate.getFullYear()}-${String(actualDate.getMonth() + 1).padStart(2, '0')}-${String(actualDate.getDate()).padStart(2, '0')}` : '未知';

                const detailContent = document.getElementById('followup-detail-content');

                detailContent.innerHTML = `
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>计划日期:</strong> ${formattedTargetDate}
                        </div>
                        <div class="col-md-6">
                            <strong>完成日期:</strong> ${formattedActualDate}
                        </div>
                    </div>

                    <div class="mb-3">
                        <strong>1. 情绪状态:</strong>
                        <p>${content.emotion_score ? content.emotion_score + '分' : '未填写'}</p>
                    </div>

                    <div class="mb-3">
                        <strong>2. 行为特征:</strong>
                        <p>
                            ${content.behaviors && content.behaviors.length > 0 ?
                                    content.behaviors.join('、') +
                                    (content.behavior_other && content.behaviors.includes('其它') ?
                                        `（${content.behavior_other}）` : '') :
                                    '无'}
                        </p>
                    </div>

                    <div class="mb-3">
                        <strong>3. 饮食记录:</strong>
                        <p>
                            ${content.diet && content.diet.length > 0 ?
                                    content.diet.map(item => {
                                        if (item === '挑食' && content.diet_picky) return `${item}（${content.diet_picky}）`;
                                        if (item === '过敏' && content.diet_allergy) return `${item}（${content.diet_allergy}）`;
                                        return item;
                                    }).join('、') :
                                '未填写'}
                        </p>
                    </div>

                    <div class="mb-3">
                        <strong>4. 睡眠质量:</strong>
                        <p>每日总时长: ${content.sleep_hours || '0'}小时; 中断次数: ${content.sleep_interruptions || '0'}次</p>
                    </div>

                    <div class="mb-3">
                        <strong>5. 胃肠反应:</strong>
                        <p>${content.gi_symptoms || '未填写'}</p>
                    </div>

                    <div class="mb-3">
                        <strong>6. 感冒生病:</strong>
                        <p>
                            ${content.illness && content.illness.length > 0 ?
                                    content.illness.map(item => {
                                        if (item === '其他' && content.illness_other) return `${item}（${content.illness_other}）`;
                                        if (item === '用药' && content.medication) return `${item}（${content.medication}）`;
                                        return item;
                                    }).join('、') :
                                '未填写'}
                        </p>
                    </div>

                    <div class="mb-3">
                        <strong>7. 咨询问题:</strong>
                        <p>${content.consultation || '无'}</p>
                    </div>
        `;

        // 显示模态框
        const modal = new bootstrap.Modal(modalElement);
        modal.show();
    }
}

// 初始化游戏
const game = new SpaceJourney();
document.addEventListener('DOMContentLoaded', () => {
    game.init();

    // 初始化星星位置
    initStarPositions();

    // 添加启动引擎按钮的点击事件监听
    const launchBtn = document.querySelector('.launch-btn');
    if (launchBtn) {
        launchBtn.addEventListener('click', handleLaunch);
    }
});

// 初始化星星位置
function initStarPositions() {
    // 获取所有星星元素
    const stars = document.querySelectorAll('.star');
    const container = document.querySelector('.twinkling-stars-container');

    if (!container) return;

    // 为每个星星设置随机位置
    stars.forEach(star => {
        const x = Math.random() * 100; // 随机 x 坐标（百分比）
        const y = Math.random() * 100; // 随机 y 坐标（百分比）
        star.style.left = `${x}%`;
        star.style.top = `${y}%`;

        // 添加随机延迟以使动画不同步
        const delay = Math.random() * 4; // 0-4秒的随机延迟
        star.style.animationDelay = `${delay}s`;
    });

    // 为流星设置随机延迟和大小
    const shootingStar = document.querySelector('.shooting-star');
    if (shootingStar) {
        const resetStar = () => {
            // 随机大小 (2-4px)
            const size = 2 + Math.random() * 2;
            shootingStar.style.width = `${size}px`;
            shootingStar.style.height = `${size}px`;

            // 尾痕长度随大小变化 (40-60px)
            const tailLength = 40 + (size - 2) * 10;
            const before = shootingStar.querySelector('::before') || shootingStar;
            before.style.width = `${tailLength}px`;

            // 随机延迟
            const delay = 2 + Math.random() * 4; // 2-6秒的随机延迟
            shootingStar.style.animationDelay = `${delay}s`;

            // 重置位置（已由 CSS transform 处理）
            shootingStar.style.opacity = '1';
        };

        // 初始化位置和大小
        resetStar();

        // 每次动画结束后重置
        shootingStar.addEventListener('animationend', resetStar);
    }
}

// 启动引擎
function handleLaunch() {

    // 如果已经设置了开始日期
    if (game.startDate) {
        const today = new Date();
        const startDate = new Date(game.startDate);

        if (startDate > today) {
            // 倒计时中
            game.showNoticeModal('提示', '如需更改发射时间，请联系导航员重新设定');
            return;
        } else {
            // 已开始，显示中止确认
            showAbortConfirmation();
            return;
        }
    }

    // 显示启动引擎模态框
    showLaunchModal();
}

// 显示启动引擎模态框
function showLaunchModal() {
    const modalElement = document.getElementById('launchModal');
    const modal = new bootstrap.Modal(modalElement, {
        backdrop: 'static',
        keyboard: false
    });

    // 设置默认日期为今天，并格式化为 YYYY-MM-DD
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    const formattedDate = `${year}-${month}-${day}`;
    document.getElementById('startDate').value = formattedDate;

    // 重置模态框状态
    document.querySelector('.launch-content').style.display = 'block';
    document.querySelector('.exit-confirmation').style.display = 'none';
    document.querySelector('.modal-footer .launch-confirm-btn').style.display = 'block';
    document.querySelector('.modal-footer .exit-confirm-btn').style.display = 'none';

    // 监听模态框隐藏事件
    modalElement.addEventListener('hidden.bs.modal', function handler() {
        modalElement.removeEventListener('hidden.bs.modal', handler);
        game.cleanupModal(modalElement);
    });

    modal.show();
}

// 显示中止确认模态框
function showAbortConfirmation() {
    const modalElement = document.getElementById('abortModal');
    const abortModal = new bootstrap.Modal(modalElement);

    // 监听模态框隐藏事件
    modalElement.addEventListener('hidden.bs.modal', function handler() {
        modalElement.removeEventListener('hidden.bs.modal', handler);
        game.cleanupModal(modalElement);
    });

    abortModal.show();
}

// 确认启动引擎
async function confirmLaunch() {
    const startDate = document.getElementById('startDate').value;
    if (!startDate) {
        game.showNoticeModal('提示', '请选择开始日期');
        return;
    }

    try {
        const response = await fetch('/apps/space-journey/start', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ startDate })
        });

        const data = await response.json();
        if (data.success) {
            // 关闭模态框
            const modalElement = document.getElementById('launchModal');
            const modalInstance = bootstrap.Modal.getInstance(modalElement);
            if (modalInstance) {
                modalInstance.hide();
            }

            // 刷新游戏状态
            await game.init();
        } else {
            game.showNoticeModal('提示', data.message || '设置开始日期失败');
        }
    } catch (error) {
        console.error('设置开始日期失败:', error);
        game.showNoticeModal('错误', '设置开始日期失败，请重试');
    }
}

// 导出全局函数
window.handleFileUpload = () => game.handleFileUpload();
window.uploadConsent = () => game.uploadConsent();
window.handleLaunch = handleLaunch;
window.confirmLaunch = confirmLaunch;
window.confirmTrialGroup = () => game.confirmTrialGroup();
window.callBase = () => game.callBase();
window.editDiary = () => game.editDiary();
window.saveDiary = () => game.saveDiary();
window.loadDiaryData = (diary) => game.loadDiaryData(diary);
window.toggleAdvancedOptions = () => game.toggleAdvancedOptions();
window.goToDiary = () => game.goToDiary();
window.goToFollowUp = () => game.goToFollowUp();
window.abortJourney = () => game.abortJourney();
window.backToCockpit = () => game.backToCockpit();
window.showHelpTip = (helpText, tipId) => game.showHelpTip(helpText, tipId);
window.removeFile = (index) => game.removeFile(index);
window.showUserInfo = () => game.showUserInfo();
window.goToJourney = () => game.goToJourney();
window.loadMoreDiaries = () => game.loadMoreDiaries();
window.showDiaryDetail = (diary) => game.showDiaryDetail(diary);
window.goToFollowUp = () => game.goToFollowUp();
window.backToCockpit = () => game.backToCockpit();
